/**
 * 
 */
package com.wqr.it.ecwdr.client.souq.reader;

import java.io.IOException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.wqr.it.ecwdr.client.dto.CountryDto;
import com.wqr.it.ecwdr.client.dto.StockDto;
import com.wqr.it.ecwdr.client.souq.parser.ProductSalesInfoListParser;
import com.wqr.it.ecwdr.client.util.WebClientUtil;

/**
 * 产品销售列表读取器
 * @author adinos
 
 */
@Service
public class ProductSalesInfoListReader {
	private static final Logger log = LoggerFactory.getLogger("INFO");
	
	@Autowired
	private ProductSalesInfoListParser parser;
	
	@Autowired
	private Map<String, CountryDto> countryMap;
	/**
	 * 获取产品销售列表
	 * @param sallerVO 销售商
	 * @param productItemVO 产品信息
	 * @return 产品销售列表
	 * @throws IOException 
	 */
	public StockDto getProductSalesInfoList (String number, int countryId) throws IOException {
		CountryDto country = countryMap.get(countryId + "");
		Assert.notNull(country, "Can't found country by " + countryId);
		String domain = country.getBaseUrl();
		String url = domain +"/a-" + number + "/io/";
		
		StockDto stockDto = new StockDto();
		stockDto.setNumber(number);
		 int i = 0;
		 String html;
	    do {
	    	i++;
			html = WebClientUtil.doGet(url, null);
			if (i > 1) {
				log.debug("Reget " + i + " / 2 ProductSalesInfoList " + url);
			}
		    //*/
			// log.info("\nURL: " + url + "\n" + html);
			if (html != null &&  html.indexOf("Robot Check") == -1) {
				parser.parse(stockDto, html, domain);
			}
	    } while(stockDto.getItemList() == null && i < 2);
		return stockDto;
	}
}
